package com.woniuxy.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author 佘赛飞
 * @create 2021-11-23 8:17 下午
 */
//上传
@Controller
public class FileOperations {
    @RequestMapping("/uploadFile")
    public ModelAndView uploadFile(HttpServletRequest request, MultipartFile multipartFile) throws IOException {
        String path = request.getServletContext().getRealPath("/images");
        String filename = UUID.randomUUID().toString() +multipartFile.getOriginalFilename();
        File file = new File(path,filename);
        multipartFile.transferTo(file);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg","上传成功");
        modelAndView.setViewName("a");
        return modelAndView;
    }
    //下载
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,@RequestParam("multipartFile") String name)
            throws UnsupportedEncodingException {
        //获取下载文件路径
        String path=request.getServletContext().getRealPath("/images")+File.separator+name;
        File file = new File(path);
        //下载显示的文件名,解决中文名称乱码的问题
        String newname = new String(name.getBytes(StandardCharsets.UTF_8), "ISO-8859-1");
        //通知浏览器以attachment(下载方式)打开图片
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",newname);
        //application/octet-stream:二进制流数据(最常见的文件下载)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
           return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
